<template>
  <div>
    <div class="header">
      <div class="header">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home/overallDisplay' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>商品</el-breadcrumb-item>
          <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="header-buttons">
        <el-button v-if="!isBatchDeleteMode" type="danger" @click="startBatchDelete">
          批量删除
        </el-button>
        <el-button type="primary" @click="showAddDialog">添加</el-button>
      </div>
    </div>

    <!-- 批量删除操作栏 -->
    <div v-if="isBatchDeleteMode" class="batch-delete-bar">
      <el-button type="danger" :disabled="!selectedRows.length" @click="confirmBatchDelete">
        删除选中项目 ({{ selectedRows.length }})
      </el-button>
      <el-button type="info" @click="cancelBatchDelete">取消</el-button>
    </div>

    <el-table :data="paginatedData" border stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column v-if="isBatchDeleteMode" type="selection" width="55" />
      <el-table-column prop="id" label="编号" width="80"></el-table-column>
      <el-table-column prop="typeName" label="分类名称"></el-table-column>
      <el-table-column prop="level" label="级别"></el-table-column>
      <!-- <el-table-column prop="unit" label="数量单位"></el-table-column> -->
      <el-table-column label="导航栏">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.shelves" @change="toggleNav(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="设置" width="270">
        <template slot-scope="scope">
        <el-button type="primary" @click="viewSub(scope.row)" :disabled="scope.row.loading">查看下一级</el-button>
        <el-button type="primary" @click="viewnext">查看上一级</el-button>

        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <div style="display: flex;">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <span class="total-count">共 {{ totalCount }} 条</span>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]" :page-size="pageSize" layout="sizes, prev, pager, next, jumper"
        :total="totalCount" />
    </div>

  <!-- 添加分类弹窗-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" :modal-append-to-body="false" :modal="false">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>

<!--选择级别-->
        <el-form-item label="级别">
          <div class="dialog-form-add-edit">
          <el-select v-model="form.addProductSortlevelChooseValue" placeholder="请选择级别"  @change="addBelongingTypeAble">
            <el-option
                v-for="item in addProductSortlevelOPtion"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
          </div>
        </el-form-item>


<!--选择所属类型 如果上一个级别是一级就禁用所属类型选择 先清空 并且把这个表disabled（放data里）禁用-->
        <el-form-item label="所属类型">
          <div class="dialog-form-add-edit">
          <el-select v-model="form.addBelongingTypeValue" placeholder="请选择所属类型">
            <el-option
                v-for="item in belongingOPtion"
                :key="item.id"
                :label="item.typeName"
                :value="item.id">
            </el-option>
          </el-select>
          </div>
        </el-form-item>


      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleClose('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { mapState } from 'vuex'
// import addBelongingTypeValue from "core-js/internals/array-iteration";

export default {
  name: "GoodsSort",
  data() {
    var validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('分类名称不能为空'));
      } else {
        callback();
      }
    };
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      dialogVisible: false,
      dialogTitle: '',
      form: {
        name: '',
        addProductSortlevelChooseValue:'',
        addBelongingTypeValue:'',

        level: '',
        unit: '',
        nav: false,
        showStatus: false,
        sort: ''
      },
      isBatchDeleteMode: false,
      selectedRows: [],
      rules:{
        name:[
            { validator: validateName, trigger: 'blur' }
        ],
      },
      // 级别选项
      addProductSortlevelOPtion:[
        { value: '1',
          label: '一级'},
        {
          value: '2',
          label: '二级'
        }
      ],

      belongingOPtion:[],



    };
  },
  computed: {
    ...mapState('goods',['Goods']),
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end);
    },
    totalCount() {
      return this.tableData.length;
    },
    ...Map
  },
  methods: {
    addBelongingTypeAble(){
      // console.log(this.form.addProductSortlevelChooseValue)
      if (this.form.addProductSortlevelChooseValue === "1"){
        this.belongingOPtion =[
          {
            "id": 0,
            "typeName": "大类无所属分类",
            "superType": 0
          }
        ]
      }
      else {
        axios.get("http://localhost:8080/Goods/getAllFirstGoodsType")
            .then((res) =>{
              // console.log(res.data.data.addBelongingTypeValue)
              const data = res.data.data.addBelongingTypeValue
              this.belongingOPtion = data
            })

      }
    },
    dialogVisibleClose(formName){
      this.$refs[formName].resetFields();
      this.dialogVisible =false
      this.form.name=''
      this.form.addBelongingTypeValue = ''
      this.form.addProductSortlevelChooseValue = ''


    },
    // addCategory() {
    //   console.log("添加分类");
    // },
    // editCategory(row) {
    //   console.log("编辑分类:", row);
    // },
    // deleteCategory(row) {
    //   console.log("删除分类:", row);
    // },
    viewSub(row) {
      console.log(row.typeName)
      this.$set(row, 'loading', true);
      axios.post("http://localhost:8080/Goods/selectGoodsTypeList").then((res)=>{
        console.log(res.data.data.goodsTypeList.length)
        for (let i = 0; i <res.data.data.goodsTypeList.length; i++) {
          console.log(res.data.data.goodsTypeList[i].typeName===row.typeName)
          if(res.data.data.goodsTypeList[i].typeName===row.typeName){
            this.tableData=res.data.data.goodsTypeList[i].children
          }
        }
        this.tableData.forEach((goodsItem)=>{
          goodsItem.level="二级"
          goodsItem.unit=row.unit
        })

      })
          .catch(error => {
            console.error("请求失败:", error);
            // 可选：显示错误消息给用户
          }).finally(() => {
        // 请求完成（成功或失败）后，移除 loading 状态，启用按钮
        this.$set(row, 'loading', false);
      });
      console.log("查看下级分类:", row.id);
    },
    transfer(row) {
      console.log("转移商品:", row);
    },
    viewnext() {
      this.getdata()
    },
    toggleShow(row) {
      console.log("切换显示状态:", row);
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
    },
    handleCurrentChange(page) {
      this.currentPage = page;
    },
    showAddDialog() {
      this.dialogTitle = '添加分类';
      this.form = {
        name: '',
        // level: '',
        // count: '',
        // unit: '',
        // nav: false,
        // showStatus: false,
        // sort: ''
      };
      axios.get("http://localhost:8080/Goods/getAllFirstGoodsType")
          .then((res) =>{
            // console.log(res.data.data.addBelongingTypeValue)
            const data = res.data.data.addBelongingTypeValue
            this.belongingOPtion = data
          })
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑分类';
      this.form = { ...row };
      if (this.form.level === "一级") {
        // console.log("这是第一种情况:", this.form);
        // console.log("这是目前的这一行的数据")
        // console.log(this.form)
        this.form.name = this.form.typeName
        this.form.addProductSortlevelChooseValue =  "一级"
        this.belongingOPtion =[
          {
            "id": 0,
            "typeName": "大类无所属分类",
            "superType": 0
          }
        ]

      } else if (this.form.level === "二级") {
        // console.log("这是第二种情况:", this.form);
        // console.log("这是目前的这一行的数据")
        // console.log(this.form)
        this.form.name = this.form.typeName
        this.form.addProductSortlevelChooseValue ="二级"
        const superType = this.form.superType.toString()
        console.log("这是superTyper 是string")
        console.log(superType)

        axios.get("http://localhost:8080/Goods/getAllFirstGoodsType")
            .then((res) =>{
              const data = res.data.data.addBelongingTypeValue
              this.belongingOPtion = data

              const addBelongingTypeValue = res.data.data.addBelongingTypeValue; // 获取数组
              console.log(res.data.data.addBelongingTypeValue)

              // 查找对应的对象
              const matchingItem = addBelongingTypeValue.find(item => item.id.toString() === superType);

              if (matchingItem) {
                console.log("找到匹配的typeName:", matchingItem.typeName);
                // 这里你可以将typeName赋值给某个变量或状态
                this.form.addBelongingTypeValue = matchingItem.typeName; // 假设有matchedTypeName用于保存结果

              } else {
                console.log("未找到匹配的typeName");
              }
            })

      }

      // if (this.form.superType || this.form.super_type != 0 )
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm('确认删除该分类?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row.id)
        const ids = []
        ids.push(row.id)
        axios.post("http://localhost:8080/Goods/deleteGoodsType", ids).then((res) => {
          res.data.data.Goods.forEach((goodsItem) => {
            if (goodsItem.super_type === 0) {
              goodsItem.level = '一级';
            }
          });
          this.tableData = res.data.data.Goods
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSubmit(formName) {
      this.$refs[formName].validate((valid) => {
            if(valid){
              console.log(valid)
              // 这是添加
              if (this.dialogTitle === '添加分类') {
                // addProductSortlevelChooseValue这个是一级就是 1 字符串
                const addProductSortlevelChooseValue= this.form.addProductSortlevelChooseValue

                if (addProductSortlevelChooseValue === "2"){
                  const superType = this.form.addBelongingTypeValue
                  // console.log("这是superType   "+superType)
                  const goodstype ={
                    "typeName":this.form.name,
                    "superType":superType
                  }
                  //   这是马上要给后端传的新type
                  //   console.log(goodstype)

                  axios.post("http://localhost:8080/Goods/addGoodsType",goodstype)
                      .then((res)=>{
                        console.log(res.data.message)
                      })
                }
                //   接下来处理addProductSortlevelChooseValue为2的
                else {
                  const goodstype ={
                    "typeName":this.form.name,
                    "superType":0
                  }
                  // 这是马上要给后端传的新type
                  // console.log(goodstype)
                  axios.post("http://localhost:8080/Goods/addGoodsType",goodstype)
                      .then((res)=>{
                        console.log(res.data.message)
                      })
                }
                window.location.reload()
              }
              // 这是编辑
              else
              {
                const superType = this.form.addBelongingTypeValue
                const goodstype ={
                  "id":this.form.id,
                  "typeName":this.form.name,
                  "superType":superType
                }
                console.log(goodstype)
                axios.post("http://localhost:8080/Goods/updateGoodsType",goodstype)
                    .then((res)=>{
                      console.log(res.data.message)
                    })



        // addProductSortlevelChooseValue这个是一级就是 1 字符串
        // const addProductSortlevelChooseValue= this.form.addProductSortlevelChooseValue
        // if (addProductSortlevelChooseValue === "2"){
        //   const superType = this.form.addBelongingTypeValue
        //   // console.log("这是superType   "+superType)
        //   const goodstype ={
        //     "id":this.form.id,
        //     "typeName":this.form.name,
        //     "superType":superType
        //   }
        //     // 这是马上要给后端传的新type
        //   console.log("这是马上要给后端传的新type")
        //     console.log(goodstype)
        //
        //   axios.post("http://localhost:8080/Goods/updateGoodsType",goodstype)
        //       .then((res)=>{
        //         console.log(res.data.message)
        //       })
        // }
        // //   接下来处理addProductSortlevelChooseValue为2的
        // else {
        //   const goodstype ={
        //     "id":this.form.id,
        //     "typeName":this.form.name,
        //     "superType":0
        //   }
        //   // 这是马上要给后端传的新type
        //   // console.log("这是马上要给后端传的新type")
        //   console.log(goodstype)
        //   axios.post("http://localhost:8080/Goods/updateGoodsType",goodstype)
        //       .then((res)=>{
        //         console.log(res.data.message)
        //       })
        // }

              }
              this.dialogVisible = false;
              this.$message({
                type: 'success',
                message: this.dialogTitle === '添加分类' ? '添加成功!' : '修改成功!'
              });
              this.$store.dispatch('productForm/SET_first_DATA', this.form)
            }else{
              console.log('error submit!!!');
              return false;
            }
      });
    },

    toggleNav(row) {
      console.log('导航栏状态改变:', row);
    },
    toggleStatus(row) {
      console.log('显示状态改变:', row);
    },
    // 开始批量删除模式
    startBatchDelete() {
      this.isBatchDeleteMode = true;
      this.selectedRows = [];
    },
    // 取消批量删除
    cancelBatchDelete() {
      this.isBatchDeleteMode = false;
      this.selectedRows = [];
    },
    // 处理表格选择变化
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    // 确认批量删除
    confirmBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的项目');
        return;
      }

      this.$confirm('确定要删除选中的项目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectedRows.map(row => row.id);
        axios.post("http://localhost:8080/Goods/deleteGoodsType", ids).then((res) => {
          res.data.data.Goods.forEach((goodsItem) => {
            if (goodsItem.super_type === 0) {
              goodsItem.level = '一级';
            }
          });
          this.tableData = res.data.data.Goods
          console.log(ids)
          this.$message({
            type: 'success',
            message: `成功删除 ${ids.length} 项`
          });
          this.selectedRows = [];
          this.isBatchDeleteMode = false;
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getdata() {
      axios.get("http://localhost:8080/Goods/selectGoodsStore").then((res) => {
        res.data.data.Goods.forEach((goodsItem) => {
          if (goodsItem.super_type === 0) {
            goodsItem.level = '一级';
          }
        });
        this.tableData = res.data.data.Goods
        this.$store.dispatch('goods/SET_DATA',res.data.data.Goods)
      })
    }
  },
  mounted() {
    this.getdata()
  }
};
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

h2 {
  margin: 0;
}

.pagination-container {
  margin: 20px 0;
  text-align: right;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
}

.total-count {
  color: #606266;
}

.batch-delete-bar {
  margin: 10px 0;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}
.dialog-form-add-edit{
  position: relative;
  right: 68px;
}
</style>
